'''
Author: gigawing
Date: 2023-02-23 12:48:36
LastEditors: gigawing
LastEditTime: 2023-02-26 16:08:37
Description: 用于处理log文件，解析指定的指令记录，并通过选项发送
'''
import requests
import argparse
import re
from datetime import datetime
import time


class ParseLog(object):
    def __init__(self, fileName, onLine) -> None:
        self.fileName_ = fileName
        self.onLine_ = onLine
        self.from_line = 0
        self.to_line = 0
        pass

    def ParseLimit(self, from_line, to_line):
        self.from_line = from_line
        self.to_line = to_line
        self.Parse()
        pass

    def Parse(self):
        file = open(self.fileName_, mode='r', encoding='utf-8')

        lines = []
        try:
            lines = file.readlines()
        finally:
            file.close()

        line_num = 0
        for line in lines:
            line_num += 1

            if self.from_line != 0 and line_num < self.from_line:
                continue
            if self.to_line != 0 and line_num > self.to_line:
                continue
            index = line.find('指令记录')
            if index != -1:
                self.onLine_(line, line_num,index)


class PrintLog (object):
    def __init__(self) -> None:
        pass

    def online(self, line, line_num):

        print(str(line_num) + ':' + line)


class SendLog (object):
    def __init__(self, address) -> None:
        self.patten = re.compile(
            r'^<(\d+)-(\d+)-(\d+) (\d+):(\d+):(\d+).(\d+)>')
        self.address_ = address
        self.lastTime = None
        pass

    def online(self, line, line_num,index):
        if (line == ''):
            return

        m = self.patten.match(line)
        if m != None:
            # print(m.group(0))
            # print("length")
            # print(m.group(1))
            # print(m.group(2))
            if len(m.group(0)) < 4:
                return

            now_time = datetime(int(m.group(1)), int(m.group(2)), int(m.group(3)),
                                int(m.group(4)), int(m.group(5)), int(m.group(6)), int(m.group(7)))
            print(str(line_num) + ":" + str(now_time))
            value_str = line[index+5:]

            # 增加对空指令的过滤
            if len(value_str) < 4:
                return

            # wait some time
            if self.lastTime != None:
                span = now_time - self.lastTime
                second_time = span.total_seconds()
                print(second_time)
                if second_time > 0:
                    time.sleep(second_time)

            self.lastTime = now_time
            print(value_str)
            if self.address_:
                requests.post(self.address_, data=bytes(
                    value_str, encoding='utf-8'), headers={'content-type': 'application/json'})
                #requests.post(self.address_, data=bytes(
                #    value_str, encoding='gb2312'), headers={'content-type': 'application/json'})
                # request.urlopen(self.address_, json=bytes(value_str,encoding='utf-8')).read().encode('utf-8')
                # self.sock_.sendto(value_str, self.address_)
                # self.sock_.sendto(bytes(value_str,encoding='utf-8'), self.address_)


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='处理log文件，按需要发送.')
    parser.add_argument('-f', action='store', help='解析的文件名', required=True)
    parser.add_argument('-url', help='发送地址', required=False,
                        type=str, default="http://127.0.0.1:3333/command")
    parser.add_argument('-s', help='起始行数', required=False, type=int, default=0)
    parser.add_argument('-e', help='停止行数', required=False, type=int, default=0)
    parser.add_argument('-t', help='仅测试文件', required=False, default=None)

    try:
        results = parser.parse_args()
        print(results)

        if results.t != None:
            p = PrintLog()
            log = ParseLog(results.f, p.online)

            log.Parse()
        else:
            han = SendLog(results.url)
            log = ParseLog(results.f, han.online)
            log.ParseLimit(results.s, results.e)

    except Exception as e:
        print(e)
        parser.print_help()
